package com.example.demo.controller;

import com.example.demo.annoation.Anonymous;
import com.example.demo.bean.AjaxRes;
import com.example.demo.bean.sysuser.SysUserDO;
import com.example.demo.context.SysContext;
import com.example.demo.dto.sysuser.LoginReqVO;
import com.example.demo.service.ISysMenuService;
import com.example.demo.service.ISysUserService;
import com.example.demo.util.RedisUtil;
import com.example.demo.dto.sysuser.LoginRepVO;
import com.example.demo.dto.sysuser.ModifyAvatarReqVO;
import com.example.demo.dto.sysuser.ModifyPwdReqVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@RestController
public class LoginController extends BaseAdminController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysMenuService sysMenuService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @Anonymous
    public AjaxRes login(@RequestBody LoginReqVO loginReqVO){
        AjaxRes ajax = new AjaxRes();
        LoginRepVO login = sysUserService.login(loginReqVO);
        ajax.put("data",login);
        ajax.put("code", HttpStatus.OK.value());
        return ajax;
    }

    @PostMapping("/logout")
    public AjaxRes logout(){
        redisUtil.deleteStringByValue(getUserId());
        SysContext.clean();
        return AjaxRes.success();
    }

    @GetMapping("/getInfo")
    public AjaxRes getInfo(){
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("menus",sysMenuService.getTreeSysMenu());
        resultMap.put("userInfo",sysUserService.getSysUser(new SysUserDO().setUserId(Long.parseLong(getUserId()))));
        resultMap.put("permissions",sysMenuService.getUserPermissions(Long.parseLong(getUserId())));
        return AjaxRes.success(resultMap);
    }

    @PutMapping("/modifyPwd")
    public AjaxRes resetPwd(@RequestBody ModifyPwdReqVO modifyPwdReqVO){
        return toAjax(sysUserService.modifyPwd(modifyPwdReqVO));
    }

    @PutMapping("/modifyAvatar")
    public AjaxRes resetPwd(@RequestBody ModifyAvatarReqVO modifyAvatarReqVO){
        return toAjax(sysUserService.modifyAvatar(modifyAvatarReqVO));
    }
}
